// UserServiceImpl.java
package com.bcu.cn.onlineexamsystem.user.service.impl;

import com.bcu.cn.onlineexamsystem.user.entity.User;
import com.bcu.cn.onlineexamsystem.user.mapper.UserMapper;
import com.bcu.cn.onlineexamsystem.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String userId, String password) {
        User user = userMapper.selectUserById(userId);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    @Override
    public boolean register(User user) {
        try {
            // 设置默认角色为学生（如果前端未传递角色）
            if (user.getRole() == null || user.getRole().isEmpty()) {
                user.setRole("student");
            }
            return userMapper.insertUser(user) > 0;
        } catch (DuplicateKeyException e) {
            // 处理重复用户ID或邮箱的情况
            return false;
        }
    }

    @Override
    public User getUserById(String userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    public boolean updateContactInfo(String userId, String email, String phone) {
        return userMapper.updateContactInfo(userId, email, phone) > 0;
    }

    @Override
    public java.util.List<java.util.Map<String, Object>> getCoursesByTeacherId(String teacherId) {
        return userMapper.findCoursesByTeacherId(teacherId);
    }

    @Override
    public java.util.List<java.util.Map<String, Object>> getClassesByTeacherId(String teacherId) {
        return userMapper.findClassesByTeacherId(teacherId);
    }
}